package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constants.SystemConstants;
import com.example.domain.ResponseResult;
import com.example.domain.entity.Article;
import com.example.domain.entity.Category;
import com.example.domain.entity.PlantCategory;
import com.example.domain.vo.ArticleDetailVo;
import com.example.domain.vo.ArticleListVo;
import com.example.domain.vo.PageVo;
import com.example.exception.FloraException;
import com.example.mapper.ArticleMapper;
import com.example.service.ArticleService;
import com.example.service.CategoryService;
import com.example.service.IPlantCategoryService;
import com.example.service.TypeService;
import com.example.utils.BeanCopyUtils;
import com.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper,Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private IPlantCategoryService plantCategoryService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private RedisCache redisCache;


    @Override
    public IPage<Article> getArticlePage(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        Page<Article> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Article> qw = new QueryWrapper();
        //正式发布的文章才能看到（非草稿）
        qw.eq("a.status",0);
        //按浏览降序
        qw.orderByDesc("a.view_count");
        //置顶文章排在前面
        qw.orderByDesc("a.is_top");

        if(condition.containsKey("title")){
            qw.like("a.title",condition.get("title"));
        }
        if(condition.containsKey("typeName")){
            qw.eq("t.name",condition.get("typeName"));
        }
        if(condition.containsKey("categoryName")){
            qw.eq("c.name",condition.get("categoryName"));
        }
        if(condition.containsKey("plantId")){
            qw.eq("a.plant_id",condition.get("plantId"));
        }

        //将浏览量设置为redis中的
        Page<Article> page1 = (Page<Article>) this.baseMapper.getArticlePage(page,qw);
//        for(Article article:page.getRecords()){
//            //从redis中获取viewCount
//            Integer viewCount = redisCache.getCacheMapValue("ArticleViewCount:", article.getId().toString());
//            article.setViewCount(viewCount.longValue());
//            //System.out.println("***************"+article.getViewCount());
//        }

        return page1;
    }
    @Override
    public List<Article> getLatestBaikeArticle() {
        return this.baseMapper.getLatestBaike();
    }

    @Override
    public List<Article> getBrowseList() {
        return baseMapper.getBrowseList();
    }

    @Override
    public List<Article> getArticleByPlantCategoryId(Long id) {
        QueryWrapper<Article> qw=new QueryWrapper<>();
        qw.eq("category_id",id);
        return baseMapper.selectList(qw);
    }

    @Override
    public Article getArticleById(Long id) {
        return baseMapper.selectById(id);
    }


    /** 点击阅读全文按钮，更新redis中的浏览量 */
    @Override
    public void updateArticleViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue2("ArticleViewCount",id.toString(),1);
    }

    @Override
    public void deleteArticle(Long id) throws FloraException {
        Article article = this.baseMapper.selectById(id);
        if(article==null){
            throw new FloraException("要删除的文章不存在");
        }
        try{
            this.baseMapper.deleteById(id);
        } catch (Exception e) {
            throw new FloraException("删除文章失败"+e.getMessage());
        }
    }


    /** 草稿文章没有浏览量（不需要从redis中获取），所以将草稿与首页获取的文章分开写 */
    @Override
    public IPage<Article> getDraftPage(Long userId, Integer pageNum, Integer pageSize) {
        Page<Article> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Article> qw = new QueryWrapper<>();
        qw.eq("a.create_by",userId);
        qw.eq("a.status",1);
        qw.orderByDesc("a.create_time");

        return this.baseMapper.getArticlePage(page,qw);
    }

    @Override
    public void updateArticle(Article article) throws FloraException {
        //先判断要修改的文章是否存在
        if(this.baseMapper.selectById(article.getId())==null){
            throw new FloraException("要修改的文章不存在");
        }

        if(judgeDataValidity(article)) {
            try {
                this.baseMapper.updateById(article);
            } catch (Exception e) {
                throw new FloraException("修改文章失败" + e.getMessage());
            }
        }
    }

    @Override
    public Article addArticle(Article article) throws FloraException {
        if(judgeDataValidity(article)){
            try {
                this.baseMapper.insert(article);
                /** 将浏览量添加到redis中 */
                redisCache.setCacheMapValue("ArticleViewCount",article.getId().toString(),0);
                return article;
            } catch (Exception e) {
                throw new FloraException("添加文章失败");
            }
        }
        return null;
    }


    //从redis中获取文章浏览量
    public Integer getArticleViewCountFromRedis(Long id){
        Integer viewCount = redisCache.getCacheMapValue("ArticleViewCount", id.toString());
        return viewCount;
    }

    //添加和修改文章时，都要先检测数据的合法性
    public Boolean judgeDataValidity(Article article) throws FloraException {
        /** 1.id>0  2.typeId存在  3.categoryId存在 */
//        if(article.getCategoryId()<0){
//            throw new FloraException("文章id错误");
//        }

//        if(typeService.getById(article.getTypeId())==null||typeService.getById(article.getTypeId()).getStatus()==1){
//            throw new FloraException("文章类型不存在");
//        }

//        if(plantCategoryService.getById(article.getCategoryId())==null|| categoryService.getById(article.getCategoryId()).getStatus()==1){
//            throw new FloraException("文章分类不存在");
//        }

        return true;
    }

    @Override
    public void updateLikeCount(Long articleId) throws FloraException {
        Article article = this.baseMapper.selectById(articleId);
        article.setLikeCount(article.getLikeCount()+1);
        try {
            this.baseMapper.updateById(article);
        } catch (Exception e) {
            throw new FloraException("更新点赞量失败");
        }
    }
}
